catalogOrderRejectionNotification
Email Template​

- 🇬🇧 English
- 🇮🇹 Italian
Function Name: catalogOrderRejectionNotification
Author: Domenico Cerone Creation Date: 02/10/2025
Last Reviewer: Domenico Cerone
Trigger: HTTPS (onRequest)
Purpose: Sends order rejection notifications to Admin users when a catalog order is rejected. This Cloud Function retrieves order details, extracts rejection reasons from associated tickets, and notifies all Admin profiles via ZeptoMail with a professional email template.
Detailed Functionality​
1. INPUT VALIDATION AND PARAMETERS​
- Required Parameter:
catalogOrderId- ID of the document in 'CatalogOrders' collection - Optional Parameter:
dryRun- If true, simulates sending without actually sending emails - Validates that catalogOrderId is provided and not empty
- Supports both real email sending and dry-run testing mode
2. CATALOG ORDER RETRIEVAL​
- Queries 'CatalogOrders' collection using the provided catalogOrderId
- Validates that the order document exists
- Extracts
profile(email) andlist_tickets_refs(array of ticket IDs) - Validates that both properties exist and list_tickets_refs is a non-empty array
3. TICKET DATA PROCESSING​
- Takes the last element from
list_tickets_refsarray (most recent ticket ID) - Queries 'Tickets' collection using the ticket ID
- Validates that the ticket document exists
- Extracts
messagesarray from ticket data - Takes the first message and extracts the
textproperty as rejection reason - Handles cases where no message text is available
4. PROFILE INFORMATION RETRIEVAL​
- Queries 'Profiles' collection using the profile email as document ID
- Extracts
firstNameandlastNamefrom profile data - Composes full name by combining firstName and lastName
- Falls back to email address if profile doesn't exist or names are empty
- Handles missing profile data gracefully
5. NOTIFICATION PREFERENCE CHECK​
- Checks if the user has enabled the catalogOrderRejectionNotification in their notification preferences
- Verifies
notification_types.catalogOrderRejectionNotificationfield in the profile - If notification is disabled (false): returns success without sending email
- If notification is enabled (true): proceeds with email sending
- Provides clear logging about notification preference status
6. ADMIN RECIPIENTS COLLECTION​
- Queries 'Profiles' collection for all documents with
role = 'Admin' - Validates that at least one Admin profile exists
- Extracts email addresses and names for each Admin
- Prepares recipient list in ZeptoMail format with email and name
7. EMAIL TEMPLATE CONFIGURATION​
- Uses ZeptoMail as the primary email service
- Template Key:
13ef.8598f19fbcc5adb.k1.ee5f0400-9d0f-11f0-9d65-dad70ff08860.19994a14040 - Sender: "no-reply@arshades.com" (ARShades Studio)
- Professional template with order details and rejection reason
8. TEMPLATE VARIABLES​
{{catalogOrdersId}}: ID of the catalog order{{profile}}: Full name of the profile (firstName lastName) instead of email{{rejectionReason}}: Text message from the ticket in list_tickets_refs
9. DRY-RUN FUNCTIONALITY​
- When
dryRun = true: Simulates the entire process without sending emails - Returns all data that would have been sent
- Useful for testing and validation
- Logs all parameters that would be used for email sending
10. ERROR HANDLING AND VALIDATION​
- Comprehensive validation at each step
- Specific error messages for missing data
- Graceful handling of missing profiles or tickets
- Detailed logging for debugging purposes
- Proper HTTP status codes for different error scenarios
11. RESPONSE STRUCTURE​
- Success response includes all processed data
- Admin recipient information
- Template variables used
- ZeptoMail result or dry-run simulation
- Detailed error information on failure
Input (Payload)​
Method: POST
Headers:
Content-Type: application/json
Body:
{
"catalogOrderId": "tTIbV3A2WqtSm8BvrHTg",
"dryRun": false
}
Parameters:
catalogOrderId(string, required): Unique identifier of the catalog order documentdryRun(boolean, optional): If true, simulates sending without actually sending emails (default: false)
Output (Success)​
{
"success": true,
"message": "Notifica di rifiuto ordine catalogo inviata con successo agli Admin",
"details": {
"catalogOrderId": "tTIbV3A2WqtSm8BvrHTg",
"profileEmail": "user@example.com",
"profileFullName": "John Doe",
"lastTicketId": "ticket123",
"rejectionReason": "Prodotto non disponibile in magazzino",
"adminRecipientsCount": 3,
"adminEmails": [
"admin1@example.com",
"admin2@example.com",
"admin3@example.com"
],
"dryRun": false
},
"zeptomail_merge_info": {
"catalogOrdersId": "tTIbV3A2WqtSm8BvrHTg",
"profile": "John Doe",
"rejectionReason": "Prodotto non disponibile in magazzino"
},
"zeptomail_result": {
"data": {
"message": "Email sent successfully"
}
}
}
Response Properties:
success(boolean): Indicates if the operation was completed successfullymessage(string): Descriptive message about the operation resultdetails(object): Detailed information about the processed datazeptomail_merge_info(object): Template variables sent to ZeptoMailzeptomail_result(object): Response from ZeptoMail service
Output (Error)​
{
"success": false,
"error": "Ordine catalogo con ID tTIbV3A2WqtSm8BvrHTg non trovato"
}
Common Error Scenarios:
- Missing catalogOrderId parameter
- Catalog order not found
- Missing profile or list_tickets_refs properties
- Ticket not found
- No Admin profiles found
- ZeptoMail service errors
Testing​
URL (if HTTPS): http://127.0.0.1:5001/arshadesstaging/europe-central2/catalogOrderRejectionNotification
Test with Emulator:
-
Start Firebase emulators:
firebase emulators:start --only functions -
Set Node.js version:
nvm use 20 -
Test with real email sending:
curl -X POST "http://127.0.0.1:5001/arshadesstaging/europe-central2/catalogOrderRejectionNotification" \
-H "Content-Type: application/json" \
-d '{"catalogOrderId": "tTIbV3A2WqtSm8BvrHTg"}' -
Test with dry-run (no email sent):
curl -X POST "http://127.0.0.1:5001/arshadesstaging/europe-central2/catalogOrderRejectionNotification" \
-H "Content-Type: application/json" \
-d '{"catalogOrderId": "tTIbV3A2WqtSm8BvrHTg", "dryRun": true}'
Postman Testing:
- Method: POST
- URL:
http://127.0.0.1:5001/arshadesstaging/europe-central2/catalogOrderRejectionNotification - Headers:
- Key:
Content-Type - Value:
application/json
- Key:
- Body: raw JSON (see examples above)
Deploy Command​
firebase deploy --only functions:catalogOrderRejectionNotification
Production URL​
Live Function: https://europe-central2-arshades-7e18a.cloudfunctions.net/catalogOrderRejectionNotification
MAIL_TEMPLATE_KEY​
- Order Rejection:
13ef.8598f19fbcc5adb.k1.ee5f0400-9d0f-11f0-9d65-dad70ff08860.19994a14040
Function Name: catalogOrderRejectionNotification
Autore: Domenico Cerone Data di creazione: 02/10/2025
Last Reviewer: Domenico Cerone
Trigger: HTTPS (onRequest)
Purpose: Invia notifiche di rifiuto ordini catalogo agli utenti Admin quando un ordine catalogo viene rifiutato. Questa Cloud Function recupera i dettagli dell'ordine, estrae i motivi del rifiuto dai ticket associati e notifica tutti i profili Admin tramite ZeptoMail con un template email professionale.
Funzionamento Dettagliato​
1. VALIDAZIONE INPUT E PARAMETRI​
- Parametro Richiesto:
catalogOrderId- ID del documento nella collezione 'CatalogOrders' - Parametro Opzionale:
dryRun- Se true, simula l'invio senza inviare realmente le email - Valida che catalogOrderId sia fornito e non vuoto
- Supporta sia l'invio reale di email che la modalità dry-run per test
2. RECUPERO ORDINE CATALOGO​
- Interroga la collezione 'CatalogOrders' usando l'ID fornito
- Valida che il documento ordine esista
- Estrae
profile(email) elist_tickets_refs(array di ID ticket) - Valida che entrambe le proprietà esistano e list_tickets_refs sia un array non vuoto
3. ELABORAZIONE DATI TICKET​
- Prende l'ultimo elemento dall'array
list_tickets_refs(ID del ticket più recente) - Interroga la collezione 'Tickets' usando l'ID del ticket
- Valida che il documento ticket esista
- Estrae l'array
messagesdai dati del ticket - Prende il primo messaggio ed estrae la proprietÃ
textcome motivo del rifiuto - Gestisce i casi in cui non è disponibile testo del messaggio
4. RECUPERO INFORMAZIONI PROFILO​
- Interroga la collezione 'Profiles' usando l'email del profilo come ID documento
- Estrae
firstNameelastNamedai dati del profilo - Compone il nome completo combinando firstName e lastName
- Fallback all'indirizzo email se il profilo non esiste o i nomi sono vuoti
- Gestisce con grazia i dati del profilo mancanti
5. CONTROLLO PREFERENZE NOTIFICHE​
- Controlla se l'utente ha abilitato catalogOrderRejectionNotification nelle sue preferenze di notifica
- Verifica il campo
notification_types.catalogOrderRejectionNotificationnel profilo - Se la notifica è disabilitata (false): restituisce successo senza inviare email
- Se la notifica è abilitata (true): procede con l'invio dell'email
- Fornisce logging chiaro sullo stato delle preferenze di notifica
6. RACCOLTA DESTINATARI ADMIN​
- Interroga la collezione 'Profiles' per tutti i documenti con
role = 'Admin' - Valida che esista almeno un profilo Admin
- Estrae indirizzi email e nomi per ogni Admin
- Prepara la lista destinatari nel formato ZeptoMail con email e nome
7. CONFIGURAZIONE TEMPLATE EMAIL​
- Utilizza ZeptoMail come servizio email principale
- Template Key:
13ef.8598f19fbcc5adb.k1.ee5f0400-9d0f-11f0-9d65-dad70ff08860.19994a14040 - Mittente: "no-reply@arshades.com" (ARShades Studio)
- Template professionale con dettagli ordine e motivo del rifiuto
8. VARIABILI TEMPLATE​
{{catalogOrdersId}}: ID dell'ordine catalogo{{profile}}: Nome completo del profilo (firstName lastName) invece dell'email{{rejectionReason}}: Messaggio di testo dal ticket in list_tickets_refs
9. FUNZIONALITÀ DRY-RUN​
- Quando
dryRun = true: Simula l'intero processo senza inviare email - Restituisce tutti i dati che sarebbero stati inviati
- Utile per test e validazione
- Registra tutti i parametri che sarebbero stati utilizzati per l'invio email
10. GESTIONE ERRORI E VALIDAZIONE​
- Validazione completa ad ogni passaggio
- Messaggi di errore specifici per dati mancanti
- Gestione elegante di profili o ticket mancanti
- Logging dettagliato per debug
- Codici di stato HTTP appropriati per diversi scenari di errore
11. STRUTTURA RISPOSTA​
- Risposta di successo include tutti i dati elaborati
- Informazioni destinatari Admin
- Variabili template utilizzate
- Risultato ZeptoMail o simulazione dry-run
- Informazioni dettagliate errore in caso di fallimento
Input (Payload)​
Metodo: POST
Headers:
Content-Type: application/json
Body:
{
"catalogOrderId": "tTIbV3A2WqtSm8BvrHTg",
"dryRun": false
}
Parametri:
catalogOrderId(string, richiesto): Identificatore unico del documento ordine catalogodryRun(boolean, opzionale): Se true, simula l'invio senza inviare realmente le email (default: false)
Output (Successo)​
{
"success": true,
"message": "Notifica di rifiuto ordine catalogo inviata con successo agli Admin",
"details": {
"catalogOrderId": "tTIbV3A2WqtSm8BvrHTg",
"profileEmail": "user@example.com",
"profileFullName": "Mario Rossi",
"lastTicketId": "ticket123",
"rejectionReason": "Prodotto non disponibile in magazzino",
"adminRecipientsCount": 3,
"adminEmails": [
"admin1@example.com",
"admin2@example.com",
"admin3@example.com"
],
"dryRun": false
},
"zeptomail_merge_info": {
"catalogOrdersId": "tTIbV3A2WqtSm8BvrHTg",
"profile": "Mario Rossi",
"rejectionReason": "Prodotto non disponibile in magazzino"
},
"zeptomail_result": {
"data": {
"message": "Email sent successfully"
}
}
}
Proprietà Risposta:
success(boolean): Indica se l'operazione è stata completata con successomessage(string): Messaggio descrittivo sul risultato dell'operazionedetails(object): Informazioni dettagliate sui dati elaboratizeptomail_merge_info(object): Variabili template inviate a ZeptoMailzeptomail_result(object): Risposta dal servizio ZeptoMail
Output (Errore)​
{
"success": false,
"error": "Ordine catalogo con ID tTIbV3A2WqtSm8BvrHTg non trovato"
}
Scenari di Errore Comuni:
- Parametro catalogOrderId mancante
- Ordine catalogo non trovato
- Proprietà profile o list_tickets_refs mancanti
- Ticket non trovato
- Nessun profilo Admin trovato
- Errori servizio ZeptoMail
Testing​
URL (if HTTPS): http://127.0.0.1:5001/arshadesstaging/europe-central2/catalogOrderRejectionNotification
Test con Emulator:
-
Avvia gli emulatori Firebase:
firebase emulators:start --only functions -
Imposta la versione Node.js:
nvm use 20 -
Test con invio email reale:
curl -X POST "http://127.0.0.1:5001/arshadesstaging/europe-central2/catalogOrderRejectionNotification" \
-H "Content-Type: application/json" \
-d '{"catalogOrderId": "tTIbV3A2WqtSm8BvrHTg"}' -
Test con dry-run (nessuna email inviata):
curl -X POST "http://127.0.0.1:5001/arshadesstaging/europe-central2/catalogOrderRejectionNotification" \
-H "Content-Type: application/json" \
-d '{"catalogOrderId": "tTIbV3A2WqtSm8BvrHTg", "dryRun": true}'
Test con Postman:
- Metodo: POST
- URL:
http://127.0.0.1:5001/arshadesstaging/europe-central2/catalogOrderRejectionNotification - Headers:
- Key:
Content-Type - Value:
application/json
- Key:
- Body: raw JSON (vedi esempi sopra)
Deploy Command​
firebase deploy --only functions:catalogOrderRejectionNotification
URL di Produzione​
Funzione Live: https://europe-central2-arshades-7e18a.cloudfunctions.net/catalogOrderRejectionNotification
MAIL_TEMPLATE_KEY​
- Order Rejection:
13ef.8598f19fbcc5adb.k1.ee5f0400-9d0f-11f0-9d65-dad70ff08860.19994a14040